import base64
import datetime
import hmac
import json
import uuid
from urllib.parse import quote
import requests
SmsId = 'LTAIIov68y5XLPal'
SmsSecret = 'ZKmJAp0AVDmSJinX7L5TSsBYps091D'
SmsSign = '瀚中企业申报'
SmsTemplate = 'SMS_193244862'
class AliyunSMS(object):
    error_handle_url = "https://help.aliyun.com/knowledge_detail/57717.html?spm=a2c4g.11186623.2.19.10446540o63rXu"

    def __init__(self):
        self.format = "JSON"
        self.version = "2017-05-25"
        self.key = SmsId
        self.secret = SmsSecret
        self.signature = ""
        self.signature_method = "HMAC-SHA1"
        self.signature_version = "1.0"
        self.signature_nonce = str(uuid.uuid4())
        self.timestamp = datetime.datetime.utcnow().isoformat("T")
        self.region_id = 'cn-hangzhou'

        self.gateway = "http://dysmsapi.aliyuncs.com"
        self.action = "SendSms"
        self.sign = ""
        self.template = ""
        self.params = {}
        self.phones = ""

    def send_single(self, phone, sign=SmsSign, template=SmsTemplate, params=""):
        self.action = "SendSms"
        self.phones = phone
        self.sign = sign
        self.params = params
        self.template = template

        query_string = self.build_query_string()

        resp = requests.get(self.gateway + "?" + query_string).json()
        return resp

    def build_query_string(self):
        query = []
        query.append(("Format", self.format))
        query.append(("Version", self.version))
        query.append(("AccessKeyId", self.key))
        query.append(("SignatureMethod", self.signature_method))
        query.append(("SignatureVersion", self.signature_version))
        query.append(("SignatureNonce", self.signature_nonce))
        query.append(("Timestamp", self.timestamp))
        query.append(("RegionId", self.region_id))
        query.append(("Action", self.action))
        query.append(("SignName", self.sign))
        query.append(("TemplateCode", self.template))
        query.append(("PhoneNumbers", self.phones))
        params = None
        if type(self.params) == str:
            params = self.params
        elif type(self.params) == dict:
            params = json.dumps(self.params)

        query.append(("TemplateParam", params))
        query = sorted(query, key=lambda key: key[0])
        query_string = ""
        i = 0
        for item in query:
            query_string += quote(item[0], safe="~") + "=" + quote(item[1], safe="~") + "&"
            i += 1
        query_string = query_string[:-1]
        tosign = "GET&%2F&" + quote(query_string, safe="~")
        secret = self.secret + "&"
        hmb = hmac.new(secret.encode("utf-8"), tosign.encode("utf-8"), "sha1").digest()
        self.signature = quote(base64.standard_b64encode(hmb).decode("ascii"), safe="~")
        query_string += "&" + "Signature=" + self.signature
        return query_string


if __name__ == '__main__':
    # s = 18235693860
    # # s = 18801543903
    # # AliyunSMS().send_single(phone=str(s),params=json.dumps({"orgname": "","batch": 20200816131422,"result": "省网账号或密码错误"}))
    # AliyunSMS().send_single(
    #     phone=str(s),
    #     params=json.dumps(
    #         {"resinfo": '常州高新技术产业开发区三维工业技术研究所有限公司，国网账号或密码错误。请前往市网重新输入正确的账号密码，激活上传。'
    #          })
    # )

    # AliyunSMS().send_single(
    #     phone=str(15295066148),
    #     sign="瀚中数据",
    #     template="SMS_217427015",
    #     # params=json.dumps(
    #     #     {"resinfo": '常州高新技术产业开发区三维工业技术研究所有限公司，国网账号或密码错误。请前往市网重新输入正确的账号密码，激活上传。'
    #     #      })
    #     params=json.dumps(
    #         {"work": "高企认定", "content": "常州中电新能电器科技有限公司", "rank": "一级"}
    #     )
    # )
    pass

